package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.components.MailService;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnums;
import net.xdclass.service.NotifyService;
import net.xdclass.utils.CheckUtils;
import net.xdclass.utils.CommonUtils;
import net.xdclass.utils.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    MailService mailService;

    private static final String SUBJECT = "驗証碼發送";

    private static final String CONTENT = "驗証碼為 %s";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public JsonData sendCode(SendCodeEnums sendCodeEnums, String to) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnums.name(), to);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        if (StringUtils.isNotBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            // 判斷是否少於60秒再次發送
            if (CommonUtils.getCurrentTimestamp() - ttl < 1000 * 60) {
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        String code = CommonUtils.getRandomCode(6);
        String value = code + "_" + CommonUtils.getCurrentTimestamp();
        redisTemplate.opsForValue().set(cacheKey, value);


        if (CheckUtils.isEmail(to)) {
            mailService.sendMail(to, SUBJECT, String.format(CONTENT, code));
            return JsonData.buildSuccess();
        }
        return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
    }

    public boolean checkCode(SendCodeEnums sendCodeEnums, String to, String code) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnums.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = cacheValue.split("_")[0];
            if (cacheCode.equals(code)) {
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }
}
